<?php

/* * ************************************************************************************************************************
 * *****                                               上传图片（可多张）                                              ********
 * *************************************************************************************************************************
 * $uploadFile 上传的图片变量
 * $savePath 保存的路径（文件夹名，如：“php”）
 * $maxSize 允许上传的图片大小，默认不限制
 * $is_condense 是否压缩图片（默认不压缩，“1”为压缩,不保存原图）
 * return 成功返回上传的图片名拼接字符串，失败则返回错误信息
 */

function uploadPhotos($uploadFile, $savePath, $maxSize = 0, $is_condense = 0) {

    //如果上传图片变量或者图片保存路径为空
    if (!$uploadFile || !$savePath) {
        return array('code' => 100, 'mess' => "上传的图片变量或者保存路径为空");
    }
    
    /* if(!$_FILES["img_upload"]){

      if($_FILES["img_upload"]["type"]!="image/gif" && $_FILES["img_upload"]["type"]!="image/png" && $_FILES["img_upload"]["type"]!="image/jpeg"){

      $this->error("图片只能上传jpg、gif、png格式！");
      exit;
      }
      } */

    //检查目录-没有则创建文件夹		
    $d = C('TMPL_PARSE_STRING');
    $root_path = "." . $d['__UPLOADS__'] . "/" . $savePath . "/";
    if (!file_exists($root_path)) {
        mkdir($root_path);
    }

    // 实例化上传类
    $upload = new \Think\Upload();

    $upload->maxSize = $maxSize; // 设置附件上传大小
    $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
    $upload->rootPath = $root_path; // 设置附件上传根目录
    $upload->saveName = array('uniqid', date("YmdHis"));
    $upload->autoSub = false;

    $info = $upload->upload();
    if ($info) {

        //拼接所有图片名称
        $save_imgs = "";
        foreach ($info as $key => $val) {
            $save_imgs.=$savePath . "/" . $val["savename"] . ",";
            //是否压缩图片
            if ($is_condense) {
                condenseImg($root_path . $val["savename"]);
            }
        }
        //返回上传的图片名拼接字符串
        return array('code' => 200, 'mess' => substr($save_imgs, 0, -1));
    } else {

        //返回错误信息
        return array('code' => 100, 'mess' => $upload->getError());
    }
}

/* 压缩图片
 * $img_path 被压缩的图片的路径
 * $type_val 压缩的数值
 * $type 压缩的类型，1为按像素，2为按比例
 */

function condenseImg($img_path, $type_val = "400", $type = "1") {

    $image = new \Think\Image();
    $image->open($img_path);

    //返回图片的宽高度
    $width = $image->width();
    $height = $image->height();

    if ($type == 1) {

        //按像素缩小
        $con_w = $type_val;
        $con_h = ceil($height / ($width / $type_val));
    } else {

        if ($type_val > 60) {

            $this->error("比例太高");
            exit;
        }

        //按比例缩小
        $con_w = $width * ($type_val / 100);
        $con_h = $height * ($type_val / 100);
    }

    //如果文件路径不存在则创建
    //$savePath_info = pathinfo($savePath);
    //if(!is_dir($savePath_info['dirname'])) mkdir ($savePath_info['dirname'], 0777);
    //覆盖原文件
    $image->thumb($con_w, $con_h)->save($img_path);

    //if($is_del) @unlink($img_path); //删除源文件
}

/* * ************************************************************************************************************************
 * *****                                               上传文件                                               ************
 * *************************************************************************************************************************
 * $uploadFile 上传的文件变量
 * $savePath 保存的路径（文件夹名，如：“php”）
 * $maxSize 允许上传的图片大小，默认不限制
 * $uploadType 设置为import代表上传类别为需要导入数据的excel表，标签name为excelData
 * return 成功返回上传的图片名拼接字符串，失败则返回错误信息
 */

function uploadFile($uploadFile, $savePath, $maxSize = 0,$uploadType="") {

    if (!$uploadFile)
        return array('code' => 100, 'mess' => "上传的图片变量或者保存路径为空");

    //检查目录-没有则创建文件夹
    $d = C('TMPL_PARSE_STRING');
    $root_path = "." . $d['__UPLOADS__']. "/" . $savePath . "/";
    if (!file_exists($root_path)) {
        mkdir($root_path);
    }

    // 实例化上传类
    $upload = new \Think\Upload();

    $upload->maxSize   = $maxSize;// 设置附件上传大小

    //如果上传的是需要导入数据的excel表
    if($uploadType=="import"){
        $upload->exts = array('xls', 'xlsx'); // 设置附件上传类型
    }
 

    $upload->rootPath = $root_path; // 设置附件上传根目录
    $upload->saveName = array('uniqid', date("YmdHis"));
    $upload->autoSub = false;


    $info = $upload->upload();

    if ($info) {

        //如果上传的是需要导入数据的excel表
        if($uploadType=="import"){
             //获取路径
            foreach ($info as $key => $val) {
                $save_file["name"] = $root_path . $val["savename"];//文件路径
                $save_file["ext"] = $val['ext'];//文件格式，用于判断导入数据         
            }

        }else{
             //获取路径
            foreach ($info as $key => $val) {
                $save_file=$savePath . "/" . $val["savename"];           
            }
        }


        //返回上传的文件信息（如果为excel，则$save_file为数组）
        return array('code' => 200, 'mess' => $save_file);
    } else {

        //返回错误信息
        return array('code' => 100, 'mess' => $upload->getError());
    }
}

//导入数据方法
/*
 * $filename 导入的文件路径
 * $exts 导入的文件格式
 */
function dataImport($filename, $exts = 'xls') {
    //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能import导入
    import("Org.Util.PHPExcel");
    //创建PHPExcel对象，注意，不能少了\
    $PHPExcel = new \PHPExcel();
    //如果excel文件后缀名为.xls，导入这个类
    if ($exts == 'xls') {
        import("Org.Util.PHPExcel.Reader.Excel5");
        $PHPReader = new \PHPExcel_Reader_Excel5();
    } else if ($exts == 'xlsx') {
        import("Org.Util.PHPExcel.Reader.Excel2007");
        $PHPReader = new \PHPExcel_Reader_Excel2007();
    }

    //载入文件
    $PHPExcel = $PHPReader->load($filename);
    //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
    $currentSheet = $PHPExcel->getSheet(0);
    //获取总列数
    $allColumn = $currentSheet->getHighestColumn();
    //获取总行数
    $allRow = $currentSheet->getHighestRow();
    //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
    for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
        //从哪列开始，A表示第一列
        for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
            //数据坐标
            $address = $currentColumn . $currentRow;
            //读取到的数据，保存到数组$arr中
            $data[$currentRow][$currentColumn] = $currentSheet->getCell($address)->getValue();
        }
    }
    return $data;
}

//导出数据方法
/*
 * $filename 导出的文件名称
 * $arrHeader 需要导出的数据列名（一维数组）
 * $arrData 需要导出的数据（二维数组）
 * $arrPhoto 导出的字段内容为图片列名（一维数组）
 * $exportType 导出的格式
 * *******************
 */
function dataExport($fileName, $arrHeader, $arrData, $arrPhoto, $exportType = 'excel') {

    //********************示例
    $arrData = M("ad_user")->field("name,user_name,user_card,user_phone,user_photo,add_time")->select();
    $arrHeader = array(
        "姓名", "账号", "身份证", "手机", "头像", "添加时间"
    );
    $fileName = "用户信息表";
    $arrPhoto = array("user_photo");
    //********************示例
    //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能import导入
    import("Org.Util.PHPExcel");

    $date = date("Y_m_d", time());
    $fileName .= "_{$date}";

    //创建PHPExcel对象，注意，不能少了\
    $objPHPExcel = new \PHPExcel();
    $objProps = $objPHPExcel->getProperties();


    //设置表头
    $header_num = ord("A");
    foreach ($arrHeader as $val) {

        $num = chr($header_num);

        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($num . '1', $val);
        $header_num += 1;
    }

    //第二行开始写入
    $col_num = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();


    foreach ($arrData as $rows) { //行写入
        $rows_num = ord("A");
        foreach ($rows as $cname => $col) {// 列写入
            $num = chr($rows_num);

            //如果为图片
            if (in_array($cname, $arrPhoto)) {
                //导出图片
                $objDrawing = new \PHPExcel_Worksheet_Drawing();
                $objDrawing->setPath('Public/uploads/' . $col);
                $objDrawing->setHeight(20);
                $objDrawing->setCoordinates($num . $col_num);
                $objDrawing->setWorksheet($objPHPExcel->getActiveSheet(0));
            } else {
                //导出数据
                $objActSheet->setCellValue($num . $col_num, $col);
            }
            $objPHPExcel->getActiveSheet()->getStyle($num . $col_num)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            $rows_num++;
        }
        $col_num++;
    }

    $fileName = iconv("utf-8", "gb2312", $fileName);
    $objPHPExcel->setActiveSheetIndex(0);

    ob_end_clean(); //清除缓冲区,避免乱码
    // 如果需要输出EXCEL格式
    if ($exportType == "excel") {

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        // 从浏览器直接输出$filename
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type: application/vnd.ms-excel;");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename=" . $fileName . ".xls");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save("php://output");
    }
    // 如果需要输出PDF格式---导出pdf格式待调试
    if ($exportType == "pdf") {


        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
        $objWriter->setSheetIndex(0);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type: application/pdf");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename=" . $fileName . ".pdf");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save("php://output");
    }
    exit;
}

/* * ************************************************************************************************************************
 * *****                                               获取分页信息                                               ************
 * *************************************************************************************************************************
  $comModel	表模型
  $where		where语句
  $order		排序字段
  $pageSize	每页显示个数
  $join	表关联
  $field	需要查询的字段
 * *********************************** */

function getPages($comModel, $where = "", $order = "id desc", $pageSize = 10, $join = "", $field = "", $distinct = "id", $group = "",$alias="") {

    //避免传参为空时被覆盖
    if(!$order) $order="id desc";
    if(!$pageSize) $pageSize="10";
    if(!$distinct) $distinct="id";

    //分页
    $count = $comModel->alias($alias)->where($where)->count($distinct);
    $Page = new \Think\Page($count, $pageSize);

    // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
    $comList = $comModel->alias($alias)->join($join)->group($group)->where($where)->order($order)->field($field)->limit($Page->firstRow . ',' . $Page->listRows)->select();

    //总页数
    $total = ceil($count / $pageSize);
    if ($_GET["p"] == $total)
        $header = "<span></span>%NOW_PAGE%/%TOTAL_PAGE%页";
    else
        $header = "%NOW_PAGE%/%TOTAL_PAGE%页";

    $Page->setConfig('header', $header);
    $Page->setConfig('prev', '&lt;');
    $Page->setConfig('next', '&gt;');
    $Page->setConfig('theme', '%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%HEADER%');

    $list["page"] = $Page->show();
    $list["comList"] = $comList;

    return $list;
}

/*
 * 获取登录用户IP
 * *******************
 */

function getUserIp() {

    if (isset($_SERVER)) {
        if ($_SERVER['SERVER_ADDR']) {
            $server_ip = $_SERVER['SERVER_ADDR'];
        } else {
            $server_ip = $_SERVER['LOCAL_ADDR'];
        }
    } else {
        $server_ip = getenv('SERVER_ADDR');
    }
    return ip2long($server_ip);
}

/*
 * 检测输入的验证码是否正确，$code为用户输入的验证码字符串
 * *******************
 */

function checkVerify($code, $id = '') {
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}


/**
 * 邮件发送函数
 */
    function sendMail($to, $title, $content) {
   
        Vendor('PHPMailer.PHPMailerAutoload');     
        $mail = new \PHPMailer(); //实例化
      
        $mail->IsSMTP(); // 启用SMTP
      
        $mail->SMTPDebug = 0; // Enable verbose debug output
        $mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->SMTPAuth = C('MAIL_SMTPAUTH'); //启用smtp认证
        $mail->Username = C('MAIL_USERNAME'); //你的邮箱名
        $mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
        $mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
        $mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
        
        $mail->AddAddress($to,"尊敬的客户");
        $mail->SMTPSecure = 'ssl'; 
        $mail->Port =  C('MAIL_PORT');
        $mail->WordWrap = 50; //设置每行字符长度
       // $mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
        $mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
        $mail->Subject =$title; //邮件主题
        $mail->Body = $content; //邮件内容
        $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示
  
        return($mail->Send());
    }
    /**
     * [curlGet description]
     * @param  [type] $url       [url数据]
     * 
     */
     function curlGet($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false);
        $fileContents = curl_exec($ch);
        if(curl_error($ch)){
            echo '有错误'.curl_error($ch);
        } 
        curl_close($ch);
        return $fileContents;
    }

    /**
     * [curlPost description]
     * @param  [type] $url       [url数据]
     * @param  [type] $postData [数组数据]
     * 
     */
     function curlPost($url,$postData){     
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false);
        if(curl_error($ch)){
            echo '有错误'.curl_error($ch);
        }        
        $fileContents = curl_exec($ch);
        curl_close($ch);
        return $fileContents;
    }

	//获取xml文件内容
	/**************************************
	$filePathName	xml文件路径名称
	*************************************/
	function getXmlConfig($filePathName){
		
		//读取xml配置文件
		if (file_exists($filePathName)) {
	
			$xml = simplexml_load_file($filePathName);
			
		} else {
			exit('Failed to open xml.');
		}
		
		foreach($xml as $k=>$v)
		{
		  	$arr[$k]=(array)$v;
		}
		
		return $arr;
	}
	
	//设置xml文件内容
	/**************************************
	$filePathName	xml文件路径名称
	$data	需要设置的数组
	*************************************/
	function setXmlConfig($filePathName,$data){
		
		$xmldata = xml_encode($data,'utf-8','schedule');  
		$res = file_put_contents($filePathName, $xmldata);
		return $res;
	}


	//二维数组排序
	/**************************************
	$arr	需排序数组
	$keys	需排序的键值
	$asc	排序规则，默认升序
	*************************************/
	function arraySort($arr,$keys,$type='asc'){ 
	
		$keysvalue = $new_array = array();
		
		foreach ($arr as $k=>$v){
		 $keysvalue[$k] = $v[$keys];
		}
		
		if($type == 'asc') asort($keysvalue);
		else arsort($keysvalue);
		
		reset($keysvalue);
		
		foreach ($keysvalue as $k=>$v){
			
			$new_array[$k] = $arr[$k];
		}
		
		return $new_array; 
	 
	}
    //下载文件
    function downFile($filePathName){

        $url='http'.(isset($_SERVER["HTTPS"]) && "on"==$_SERVER["HTTPS"] ? 's':'');
        $downfile=$url."://".$_SERVER['SERVER_NAME']."/Uploads/push/".$filePathName;

        //$Http = new \Org\Net\Http();
        //$tu = date("YmdHis",time()) . "_" . rand(100, 50000) . ".png";
        //$Http->curlDownload($downfile, "C:/Users/Administrator/Desktop/".$tu);

        $fileinfo = pathinfo($downfile);
        header('Content-type: application/x-'.$fileinfo['extension']);
        header('Content-Disposition: attachment; filename='.$fileinfo['basename']);
        header('Content-Length: '.filesize($downfile));
        readfile($thefile);
        exit;
    }


    //获取代写状态
    function getWriteStatus(){

        $status["apply"]=array("未审核","已通过","未通过");
        $status["ok"]=array("未完成","已完成");

        return $status;
    }
    //获取云推送状态
    function getPushStatus(){

        $status["apply"]=array("未审核","已通过","未通过");
        $status["ok"]=array("未完成","已完成");

        return $status;
    }
